import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { EntityManager, In } from 'typeorm';
import { User } from './entities/user.entity';
import { InjectEntityManager } from '@nestjs/typeorm';
import { Role } from './entities/role.entity';
import { Permission } from './entities/permission.entity';
import { UserLoginDto } from './dto/user-login.dto';

@Injectable()
export class UserService {
  @InjectEntityManager()
  entityManager: EntityManager;

  async initData() {
    const user1 = new User();
    user1.username = '张三';
    user1.password = '111111';

    const user2 = new User();
    user2.username = '李四';
    user2.password = '222222';

    const user3 = new User();
    user3.username = '王五';
    user3.password = '333333';

    const role1 = new Role();
    role1.value = 'admin';
    role1.status = 1;

    const role2 = new Role();
    role2.value = 'user';
    role2.status = 1;

    const permission1 = new Permission();
    permission1.permission = 'user:create';

    const permission2 = new Permission();
    permission2.permission = 'user:update';

    const permission3 = new Permission();
    permission3.permission = 'user:delete';

    const permission4 = new Permission();
    permission4.permission = 'user:view';

    role1.permissions = [permission1, permission2, permission3, permission4];
    role2.permissions = [permission4];

    user1.roles = [role1];
    user2.roles = [role2];
    user3.roles = [role2];
    await this.entityManager.save(Permission, [
      permission1,
      permission2,
      permission3,
      permission4,
    ]);
    await this.entityManager.save(Role, [role1, role2]);

    await this.entityManager.save(User, [user1, user2, user3]);
  }
  async login(loginUserDto: UserLoginDto) {
    const user = await this.entityManager.findOne(User, {
      where: {
        username: loginUserDto.username,
      },
      relations: {
        roles: true,
      },
    });

    if (!user) {
      throw new HttpException('用户不存在', HttpStatus.ACCEPTED);
    }

    if (user.password !== loginUserDto.password) {
      throw new HttpException('密码错误', HttpStatus.ACCEPTED);
    }

    return user;
  }
  async findPermissonByRoleId(roleId: number[]) {
    return this.entityManager.find(Role, {
      where: { id: In(roleId) },
      relations: { permissions: true },
    });
  }
}
